import { memo, useEffect, useMemo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import {
  Avatar,
  Badge,
  Button,
  Comment,
  Form,
  Input,
  Segmented,
  Tooltip,
} from 'antd';
import { resOrdersComment } from '@/services/orders';
import { userStore } from '@/store/userStore';
import { useRequest } from 'ahooks';
import { useRecoilValue } from 'recoil';
import BooksCommentItem from '@/components/BooksCommentItem';
import { formatUrl } from '@/utils/format';

interface EditorProps {
  onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
  onSubmit: () => void;
  submitting: boolean;
  value: string;
}

const Editor: FC<PropsWithChildren<EditorProps>> = ({
  onChange,
  onSubmit,
  submitting,
  value,
}) => (
  <>
    <Form.Item>
      <Input.TextArea rows={3} onChange={onChange} value={value} />
    </Form.Item>
    <Form.Item className={'text-right'}>
      <Button
        htmlType="submit"
        loading={submitting}
        onClick={onSubmit}
        type="primary"
      >
        发布评论
      </Button>
    </Form.Item>
  </>
);

const OrdersComment: FC<
  PropsWithChildren<{ source: API.OrdersDetailResult; refresh: Function }>
> = ({ source, refresh }) => {
  const userinfo = useRecoilValue(userStore);
  const [value, setValue] = useState('');
  const [goodsId, setGoodsId] = useState(0);

  useEffect(() => {
    setGoodsId(
      source.orders_detail.length > 0 ? source.orders_detail[0].id : 0
    );
  }, [source]);

  const options = useMemo(() => {
    return source.orders_detail.map((value) => ({
      label: (
        <Tooltip title={value.goods.description}>{value.goods.title}</Tooltip>
      ),
      value: value.goods_id,
    }));
  }, [source]);

  const { loading, runAsync } = useRequest(resOrdersComment, { manual: true });
  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setValue(e.target.value);
  };
  const handleSubmit = () => {
    runAsync(source.id, { goods_id: goodsId, content: value }).then(() => {
      refresh();
      setValue('');
    });
  };
  return (
    <div className={'pt-5 px-5'}>
      <Badge status={'success'} /> 请选择要评价的商品：
      <Segmented
        options={options}
        value={goodsId}
        onChange={(value) => {
          setGoodsId(value as number);
        }}
      />
      <Comment
        avatar={<Avatar size={'large'} src={userinfo.avatar} alt="avatar" />}
        content={
          <Editor
            onChange={handleChange}
            onSubmit={handleSubmit}
            submitting={loading}
            value={value}
          />
        }
      />
      <div>
        {source?.comment && source.comment.length > 0 ? (
          <div className={'pt-8 px-4'}>
            {source.comment?.map((value) => (
              <BooksCommentItem data={value} key={value.id} />
            ))}
          </div>
        ) : null}
      </div>
    </div>
  );
};

export default memo(OrdersComment);
